package com.heima.search.listen;

import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author mrchen
 * @date 2022/1/12 10:59
 */
@Component
@Slf4j
public class ArticleAddOrRemoveListener {
    @Autowired
    ArticleSearchService articleSearchService;
    @Autowired
    ArticleFeign articleFeign;

    @RabbitListener(queuesToDeclare = @Queue(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE))
    public void addArticle(String articleId){
        log.info(" 接收到文章上架消息   文章的id ==> {}",articleId);
        ResponseResult<SearchArticleVO> articleResult = articleFeign.findArticle(Long.valueOf(articleId));
        if (!articleResult.checkCode()) {
            log.error("远程调用 查询文章接口失败 原因: {}",articleResult.getErrorMessage());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,articleResult.getErrorMessage());
        }
        SearchArticleVO data = articleResult.getData();
        if (data == null) {
            log.error("远程调用 未查询到文章信息 文章id: {}",articleId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到文章信息");
        }
        articleSearchService.saveArticle(data);
    }
    @RabbitListener(queuesToDeclare = @Queue(NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE))
    public void deleteArticle(String articleId){
        log.info(" 接收到文章下架消息   文章的id ==> {}",articleId);
        articleSearchService.deleteArticle(articleId);
    }
}